﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace Edex2IBS
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string IBSConnectionString = String.Empty;
        string HQCConnectionString = String.Empty;
        string ApiURI = String.Empty;
        string login = String.Empty;
        string password = String.Empty;
        string RootUri = String.Empty;
        string PetrolKey = String.Empty;
        string TnkKey = String.Empty;
        string path4RPO = String.Empty;
        string path4IbsImport = String.Empty;
        IBS.IbsDataContext ibs;
        HQC.HqcDataContext hqc;
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                IBSConnectionString = Properties.Settings.Default.IBSConnectionString;
                HQCConnectionString = Properties.Settings.Default.HQCConnectionString;
                ApiURI = Properties.Settings.Default.ApiUri;
                RootUri = Properties.Settings.Default.RootUri;
                login = Properties.Settings.Default.LOGIN;
                password = Properties.Settings.Default.PASSWORD;
                PetrolKey = Properties.Settings.Default.PetrolKey;
                TnkKey = Properties.Settings.Default.TNKKey;
                ibs = new IBS.IbsDataContext(IBSConnectionString);
                hqc = new HQC.HqcDataContext(HQCConnectionString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //Выгрузка справочника поставщиков в EDEX
            var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);

            if (Radio_IBS.IsChecked == true)
            {
                try
                {                    
                    edex.ChangeCompany(PetrolKey); //petrol
                    try
                    {
                        //Загрузка справочника компаний BP                   
                        var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateBP_Suppliers").AddYears(-2);
                        var suppliers = ibs.GetSuppliers(LastSyncDate).ToList();                        
                        if (suppliers.Count > 0)
                        {
                            var existingSuppliers = edex.GetSuppliers();
                            foreach (var supplier in suppliers)
                            {
                                EdexApiClient.WH_COMPANIES sup = new EdexApiClient.WH_COMPANIES()
                                {
                                    EXT_KEY = supplier.SUPIBSCODE.ToString(),
                                    COMPANY_NAME = supplier.SUPNAME
                                };

                                if (existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).Any())
                                {
                                    sup.GUID_RECORD = existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                    edex.UpdateSupplier(sup);
                                }
                                else
                                    edex.AddSupplier(sup);
                            }
                        }
                        //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
                if (Radio_HQC.IsChecked == true)
                {
                    try
                    {
                        edex.ChangeCompany(TnkKey); //petrol
                        try
                        {
                            //Загрузка справочника компаний BP                   
                            var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Suppliers").AddYears(-2);
                            var suppliers = hqc.GetSuppliers(LastSyncDate).ToList();
                            if (suppliers.Count > 0)
                            {
                                var existingSuppliers = edex.GetSuppliers();
                                foreach (var supplier in suppliers)
                                {
                                    EdexApiClient.WH_COMPANIES sup = new EdexApiClient.WH_COMPANIES()
                                    {
                                        EXT_KEY = supplier.ID_Record.ToString(),
                                        COMPANY_NAME = supplier.SupplierName
                                    };

                                    if (existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).Any())
                                    {
                                        sup.GUID_RECORD = existingSuppliers.Where(r => r.EXT_KEY == sup.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                        edex.UpdateSupplier(sup);
                                    }
                                    else
                                        edex.AddSupplier(sup);
                                }
                            }
                            //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            //Выгрузка справочника товара в EDEX
            var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);

            if (Radio_IBS.IsChecked == true)
            {
                try
                {
                    edex.ChangeCompany(PetrolKey); //petrol
                    try
                    {
                        var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateBP_Items").AddYears(-2);
                        var items = ibs.GetItems(LastSyncDate).ToList();
                        if (items.Count > 0)
                        {
                            var existingitems = edex.GetItems();
                            foreach (var item in items)
                            {
                                EdexApiClient.WH_ITEMS itm = new EdexApiClient.WH_ITEMS()
                                {
                                    EXT_KEY = item.ITEMCODE.ToString(),
                                    ITEM_NAME = item.SHORTNAME
                                };

                                if (existingitems.Where(r => r.EXT_KEY == itm.EXT_KEY).Any())
                                {
                                    itm.GUID_RECORD = existingitems.Where(r => r.EXT_KEY == itm.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                    edex.UpdateItem(itm);
                                }
                                else
                                    edex.AddItem(itm);
                            }
                        }
                        //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
                if (Radio_HQC.IsChecked == true)
                {
                    try
                    {
                        edex.ChangeCompany(TnkKey); //petrol
                        try
                        {
                            //Загрузка справочника компаний BP                   
                            var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Items").AddYears(-2);
                            var items = hqc.GetItems(LastSyncDate).ToList();
                            if (items.Count > 0)
                            {
                                var existingItems = edex.GetItems();
                                foreach (var item in items)
                                {
                                    EdexApiClient.WH_ITEMS itm = new EdexApiClient.WH_ITEMS()
                                    {
                                        EXT_KEY = item.ID_Record.ToString(),
                                        ITEM_NAME = item.ItemName
                                    };

                                    if (existingItems.Where(r => r.EXT_KEY == itm.EXT_KEY).Any())
                                    {
                                        itm.GUID_RECORD = existingItems.Where(r => r.EXT_KEY == itm.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                        edex.UpdateItem(itm);
                                    }
                                    else
                                        edex.AddItem(itm);
                                }
                            }
                            //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            //Выгрузка справочника станций в EDEX
             var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);
             if (Radio_IBS.IsChecked == true)
             {
                 try
                 {                    
                     edex.ChangeCompany(PetrolKey); //petrol
                     try
                     {
                         var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateBP_Sites").AddYears(-2);
                         var sites = ibs.GetSites(LastSyncDate).ToList();
                         if (sites.Count > 0)
                         {
                             var existingsites = edex.GetLocations();
                             foreach (var site in sites)
                             {
                                 EdexApiClient.WH_LOCATIONS loc = new EdexApiClient.WH_LOCATIONS()
                                 {
                                     EXT_KEY = site.SITEIBSCODE.ToString(),
                                     LOCATION_NAME = site.RCCODE + " " + site.SITENAME,
                                     STREET = site.ADDRESS,
                                     IS_DEFAULT = false
                                 };

                                 if (existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).Any())
                                 {
                                     loc.GUID_RECORD = existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                     edex.UpdateLocation(loc);
                                 }
                                 else
                                     edex.AddLocation(loc);
                             }
                         }
                         //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }

                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show(ex.Message);
                 }
             }
             else
                 if (Radio_HQC.IsChecked == true)
                 {
                     try
                     {
                         edex.ChangeCompany(TnkKey); //petrol
                         try
                         {
                             //Загрузка справочника компаний BP                   
                             var LastSyncDate = ibs.GetLastSyncDate("LastSyncDateTNK_Sites").AddYears(-2);                            
                             var sites = hqc.GetSites(LastSyncDate).ToList();
                             if (sites.Count > 0)
                             {
                                 var existingsites = edex.GetLocations();
                                 foreach (var site in sites)
                                 {
                                     EdexApiClient.WH_LOCATIONS loc = new EdexApiClient.WH_LOCATIONS()
                                     {
                                         EXT_KEY = site.ID_Record.ToString(),
                                         LOCATION_NAME = site.LocationName,
                                         STREET = site.Address,
                                         IS_DEFAULT = false
                                     };

                                     if (existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).Any())
                                     {
                                         loc.GUID_RECORD = existingsites.Where(r => r.EXT_KEY == loc.EXT_KEY).FirstOrDefault().GUID_RECORD;
                                         edex.UpdateLocation(loc);
                                     }
                                     else
                                         edex.AddLocation(loc);
                                 }
                             }
                             //ibs.SetLastSyncDate(now.ToString("dd.MM.yyyy HH:mm:ss"), "LastSyncDateBP_Suppliers");
                         }
                         catch (Exception ex)
                         {
                             MessageBox.Show(ex.Message);
                         }

                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.Message);
                     }
                 }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            if (Radio_RPO.IsChecked == true)
            {
                try
                {
                    //формирование RPO
                    path4RPO = Properties.Settings.Default.path4RPO;

                    if (!Directory.Exists(path4RPO))
                        Directory.CreateDirectory(path4RPO);

                    var SaleOrderList = ibs.GetSaleOrders(IBS.IMPORTTYPE.RPO);

                    foreach (var saleOrder in SaleOrderList)
                    {
                        try
                        {
                            var RPO_data = ibs.GetRPO(saleOrder.INVOICE_ID);
                            foreach (var line in RPO_data)
                            {
                                if (!Directory.Exists(path4RPO + @"\" + line.IP))
                                    Directory.CreateDirectory(path4RPO + @"\" + line.IP);
                                line.SerializeToFile(path4RPO + @"\" + line.IP + @"\RPO_Invoice_" + line.LOCATION_KEY + "_" + line.SUPPLIERCODE + "_" + line.INVOICECODE + "_" + line.INVOICEDATE.ToString("ddMMyyyy") + ".1");
                            }
                            ibs.UpdateStatus(saleOrder.INVOICE_ID);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.None);
                        }

                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
                if (Radio_IbsImport.IsChecked == true)
                {
                    try
                    {
                        var path2IbsImport = Properties.Settings.Default.path4IbsImport;

                        if (!Directory.Exists(path2IbsImport))
                            Directory.CreateDirectory(path2IbsImport);

                        var SaleOrderList = ibs.GetSaleOrders(IBS.IMPORTTYPE.IbsImport);

                        foreach (var saleOrder in SaleOrderList)
                        {
                            try
                            {
                                var ibsImportData = ibs.GetIBSImport(saleOrder.INVOICE_ID);
                                foreach (var line in ibsImportData)
                                {
                                    if (!Directory.Exists(path2IbsImport + @"\" + line.SITEIBSCODE))
                                        Directory.CreateDirectory(path2IbsImport + @"\" + line.SITEIBSCODE);
                                    line.SerializeToFile(path2IbsImport + @"\" + line.SITEIBSCODE + @"\" + line.COMPANY_KEY + "_" + line.DOC_NUMBER + "_" + line.DOC_DATE.ToString("yyyy.MM.dd") + ".txt");
                                }
                                ibs.UpdateStatus(saleOrder.INVOICE_ID);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.None);
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.None);

                    }
                }
           
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            try
            {
                ////тестовая загрузка 1го файла
                string path = @"\\msk-hqdb-01.retail.tnk-bp.ru\HQCUpload\Supplier_Code\";
                string connectionString = "Data Source=ORAIBS.WIN;User ID=ibsdbo;Password=campator;";
                var files = Directory.GetFiles(path, "Supplier_Code*.txt", SearchOption.TopDirectoryOnly);
                var ibs = new IBS.IbsDataContext(connectionString);

                foreach (var file in files)
                {
                    try
                    {
                        FileInfo fi = new FileInfo(file);
                        var parser = new IBS.Parser(fi.FullName);
                        var result = parser.parseFile();

                        ibs.DeleteHQCSupplierCode(result.FirstOrDefault().SITECODE);
                        foreach (IBS.HQCSUPPLIER_CODE line in result)
                        {
                            try
                            {
                                ibs.SaveHQCSupplierCode(line);
                            }
                            catch (Exception ex)
                            { }
                        }
                    }
                    catch (Exception ex)
                    { }

                }
            }
            catch (Exception ex)
            { }
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            //загрузка накладных в IBS
            var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);
            edex.ChangeCompany(TnkKey);
            var invoices = edex.GetNewIncomingInvoices();

            var stream = edex.GetIncomingInvoicesCommerceML(invoices.Select(r => r.GUID_RECORD).ToArray());
            var xml = new System.IO.StreamReader(stream).ReadToEnd();

            new CommerceML2IBS.IntegrationContext(IBSConnectionString).Process(xml);
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            //загрузка накладных в IBS
            var edex = new EdexApiClient.EdexApiContext(ApiURI, RootUri, login, password);
            edex.ChangeCompany(PetrolKey);
            var invoices = edex.GetNewIncomingInvoices();

            invoices.ToList().ForEach(r =>
            {
                try
                {
                    var stream = edex.GetIncomingInvoicesCommerceML(r.GUID_RECORD);
                    var xml = new System.IO.StreamReader(stream).ReadToEnd();

                    var context = new CommerceML2IBS.IntegrationContext(IBSConnectionString);

                    context.ProcessedDocument += ((sender1, e1) =>
                    {
                        edex.SetIncomingNumber(e1.Id, e1.IncomingNumber);
                    });

                    context.Process(xml);
                }
                catch (Exception ex) { }
            });

        }
    }
}
